import { _decorator, Component, input, Input, EventKeyboard, Node, KeyCode, Vec2, director,Sprite,
    Vec3,BoxCollider2D,IPhysics2DContact,Contact2DType,Label,find,color } from 'cc';

const { ccclass, property } = _decorator;
import { SpineTs } from './SpineTs';
import { createEnemy } from './createEnemy';
import { Weapon } from './Weapon';
import { Fireball } from './Fireball';
import { buff } from './buff';
import { Enemy } from './Enemy';
import { EnemyATK } from './EnemyATK';
import { boss } from './boss';
import GlobalData from './GlobalData';
// 从本地数据中读取玩家上轮最高得分数据，如果没有则默认0
let lastScore = window.localStorage.getItem('lastScore') || 0;
@ccclass('PlayerController')
export class PlayerController extends Component {
    // spineTs节点
    // @property(SpineTs)
    // private spineTs:SpineTs = null;
    // createEnemy节点
    @property(createEnemy)
    private createEnemy:createEnemy = null;

    // 游戏结束界面
    @property(Node)
    gameOverNode:Node = null;
    
    // 武器挂载节点
    @property(Node)
    weaponNode:Node = null;
    // 火球挂载节点
    @property(Node)
    fireballNode:Node = null;
    
    // 是否启用对角线移动标准化（防止斜向移动更快）
    @property
    public normalizeDiagonal: boolean = true;
    // 武器中心节点
    @property({type:Node})
    weaponCenter:Node = null;
    // 火球中心节点
    @property({type:Node})
    fireballCenter:Node = null;
    // buff节点中心
    @property(Node)
    buffNode:Node = null;
    // 敌人挂载节点
    @property(Node)
    enemyNode:Node = null;
    // boss攻击光波挂载节点
    // @property(Node)
    // guangboNode:Node = null;

    // 血量节点
    @property(Node)
    healthNode:Node = null;

    // 碰撞组件
    private collider: BoxCollider2D = null;
    // 按键状态记录
    private keyState: Map<KeyCode, boolean> = new Map();
    
    // 移动方向
    private movement: Vec2 = new Vec2(0, 0);
    // 是否停止移动
    private isStop = false

    // 玩家持有武器数量(初始为1)
    public weaponNums = 1
    // 玩家持有火球数量(初始为0)
    public fireballNums = 0
    // 武器攻击力(初始为10)
    public attack = 10
    // 武器转动速度
    public rotateSpeed = 10
    // 火球攻击力(初始为50)
    public FireAttack = 50
    // 火球转动速度
    public FireRotateSpeed = 100
    // 玩家血量
    public health = 100
    // 游戏状态：是否已死亡
    private isDead = false
    // 玩家已获得的百分比伤害值
    public percent = 0

    public moveSpeed: number = 300;

    onLoad() {
        // 初始化按键状态
        this.keyState.set(KeyCode.KEY_W, false);
        this.keyState.set(KeyCode.KEY_A, false);
        this.keyState.set(KeyCode.KEY_S, false);
        this.keyState.set(KeyCode.KEY_D, false);
        // 隐藏游戏结算界面
        // this.gameOverNode.active = false
    }

    start() {
        // 监听键盘事件
        input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.on(Input.EventType.KEY_UP, this.onKeyUp, this);
        // 获取碰撞组件
        this.collider = this.getComponent(BoxCollider2D);
        if (this.collider) {
            // 注册碰撞回调
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
    }

    onDestroy() {
        // 移除事件监听
        input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.off(Input.EventType.KEY_UP, this.onKeyUp, this);
    }

    private onKeyDown(event: EventKeyboard) {
        this.keyState.set(event.keyCode, true);
        this.updateMovement();
    }

    private onKeyUp(event: EventKeyboard) {
        this.keyState.set(event.keyCode, false);
        this.updateMovement();
    }

    private updateMovement() {
        // 重置移动向量
        this.movement.set(Vec2.ZERO);
        
        // 根据按键状态更新移动方向
        if (this.keyState.get(KeyCode.KEY_W)) {
            this.movement.y += 1; // 上
        }
        if (this.keyState.get(KeyCode.KEY_S)) {
            this.movement.y -= 1; // 下
        }
        if (this.keyState.get(KeyCode.KEY_A)) {
            // this.node.setScale(-.1,.1);
            this.movement.x -= 1; // 左
        }
        if (this.keyState.get(KeyCode.KEY_D)) {
            // this.node.setScale(.1,.1);
            this.movement.x += 1; // 右
        }
        
        // 标准化对角线移动，确保各方向速度一致
        if (this.normalizeDiagonal && this.movement.length() > 0) {
            this.movement.normalize();
        }
    }

    update(deltaTime: number) {
        // 如果玩家已死亡，停止所有更新
        if (this.isDead) {
            return;
        }

        // 如果有移动输入，则更新位置
        if (this.movement.length() > 0) {
            this.isStop = false
            const currentPos = this.node.getPosition();
            const newPos = new Vec3(
                currentPos.x + this.movement.x * this.moveSpeed * deltaTime,
                currentPos.y + this.movement.y * this.moveSpeed * deltaTime,
                currentPos.z
            );
            const weaponCenterPos = new Vec3(
                currentPos.x + this.movement.x * this.moveSpeed * deltaTime,
                // currentPos.y + this.movement.y * this.moveSpeed * deltaTime + 35,
                currentPos.y + this.movement.y * this.moveSpeed * deltaTime,
                currentPos.z
            );
            const buffPos = weaponCenterPos
            const fireballCenterPos = weaponCenterPos
            // 修改各节点位置
            this.node.setPosition(newPos);
            this.weaponCenter.setPosition(weaponCenterPos)
            this.fireballCenter.setPosition(fireballCenterPos)
            // this.guangboNode.setPosition(weaponCenterPos)
            this.buffNode.setPosition(buffPos)
            // this.gameOverNode.setPosition(newPos)
            // 播放行走动画
            // this.spineTs.getComponent(SpineTs).walk();
        }
        if(this.isStop)return
        if(this.movement.length() == 0){
            // this.spineTs.getComponent(SpineTs).blink();
            this.isStop = true
            // console.log("Stop")
            return
        }
    }
    // 碰撞开始回调
    private onBeginContact(selfCollider: BoxCollider2D, otherCollider: BoxCollider2D, contact: IPhysics2DContact | null) {
        // console.log("发生碰撞，碰撞对象组为:",otherCollider.group)
        // 检查碰撞对象是否是敌人
        if (otherCollider.group === 4) { // 敌人的碰撞分组为 4
            const enemy = otherCollider.node.getComponent(Enemy);
            if (enemy) {
                this.onHitEnemy(enemy);
            }
        }
        // 检查碰撞对象是否是boss
        if (otherCollider.group === 16) { // boss的碰撞分组为 16
            const bossHit = otherCollider.node.getComponent(boss);
            if (bossHit) {
                this.onHitEnemy(bossHit);
            }
        }
        // 检查碰撞对象是否是boss的攻击
        if (otherCollider.group === 32) { // boss的攻击碰撞分组为 32
            const bossATK = otherCollider.node.getComponent(EnemyATK);
            if (bossATK) {
                this.onHitEnemy(bossATK);
            }
        }
    }

    // 被敌人击中
    private onHitEnemy(enemy: any) {
        // 如果已经死亡，不再处理伤害
        if (this.isDead) return;
        this.health -= enemy.attack
        this.healthNode.children[1].getComponent(Label).string = this.health.toString()
        this.node.getComponent(Sprite).color = color(255,0,0)
        setTimeout(()=>{
            if(this.node){
                this.node.getComponent(Sprite).color = color(255,255,255)
            }
        },200)
        if(this.health <= 0){
            this.gameOver();
        }
    }

    // 游戏结束处理
    private gameOver() {
        if (this.isDead) return; // 防止重复调用
        this.isDead = true;
        // 修改游戏结束面板的本轮游戏得分
        this.gameOverNode.children[1].children[1].getComponent(Label).string = this.buffNode.getComponent(buff).score.toString()
        // 清理所有定时器和事件监听
        this.cleanupAllTimers();
    }

    // 清理所有定时器
    private cleanupAllTimers() {
        this.buffNode.getComponent(buff).updateHistoryScore()
        // 注销所有定时器
        this.createEnemy.getComponent(createEnemy).stopCreate()
        for(var i = 0;i<this.weaponNums;i++){// 武器旋转定时
            clearInterval(this.weaponCenter.children[i].getComponent(Weapon).weaponRunTimer)
        }
        for(var i = 0;i<this.fireballNums;i++){// 火球旋转定时
            clearInterval(this.fireballCenter.children[i].getComponent(Fireball).FireballRunTimer)
        }
        for(var i = 0;i<this.enemyNode.children.length;i++){// 普通敌人灼烧定时器，boss发射光波定时器
            if(this.enemyNode.children[i].getComponent(Enemy)&&this.enemyNode.children[i].getComponent(Enemy).burnTimer){
                clearInterval(this.enemyNode.children[i].getComponent(Enemy).burnTimer)
            }
            // boss攻击定时器
            if(this.enemyNode.children[i].getComponent(boss)&&this.enemyNode.children[i].getComponent(boss).bossATKTimer){
                clearInterval(this.enemyNode.children[i].getComponent(boss).bossATKTimer)
            }
        }
        lastScore = this.buffNode.getComponent(buff).score.toString()
        window.localStorage.setItem('lastScore', lastScore)
        console.log(lastScore,"lastScore")
        // 跳转到游戏结束场景
        // director.loadScene('scene/gameOver');
        // 展示游戏结束界面
        this.gameOverNode.active = true
    }
}